<template>
  <div class="app-container">
    <div
      class="header"
      style="display: flex; justify-content: space-between"
    >
      <el-form
        :model="queryParams"
        ref="queryRef"
        :inline="true"
        v-show="showSearch"
      >
        <el-form-item>
          <el-button
            icon="refresh"
            color=" rgb(69, 76, 105)"
            style="color: #fff"
            @click="resetQuery()"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            @click="handleAdd"
            v-hasPermi="['system:car:add']"
            style="padding: 0 20px"
          >
            新 增
          </el-button>
        </el-form-item>
      </el-form>
      <el-form
        :model="queryParams"
        ref="queryRef"
        :inline="true"
        v-show="showSearch"
      >
         <!-- 时间选择 -->
         <!-- <el-form-item label="">
          <el-date-picker
            v-model="searchtime"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd HH:mm:ss"
            @change="onDateChange"
          />
        </el-form-item> -->
        <el-form-item
          label=""
          prop="title"
        >
          <el-date-picker
            v-model="searchtime"
            type="datetimerange"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="info"
            icon="Search"
            @click="handleQuery()"
          />
        </el-form-item>
      </el-form>
    </div>

    <el-table
      v-loading="loading"
      :data="carouselList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        label="所在页面"
        align="center"
        prop="belongPage"
      />
      <el-table-column
        label="轮播图图片"
        align="center"
        prop="carouselImg"
      >
        <template #default="scope">
          <el-image
            :src="scope.row.carouselImg"
            style="width: 100px; height: 100px"
            fit="contain"
          >
          </el-image>
        </template>
      </el-table-column>
      <el-table-column
        label="跳转地址"
        align="center"
        prop="jumpDestination"
      >
        <template #default="scope">
          <a :href="scope.row.jumpDestination">{{
            scope.row.jumpDestination
          }}</a>
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="180"
      >
        <template #default="scope">
          <span>{{
            parseTime(scope.row.createTime, "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:carousel:edit']"
            >编辑</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:carousel:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改轮播图对话框 -->
    <el-dialog
      :title="title"
      v-model="open"
      width="500px"
      append-to-body
      @close="cancel"
    >
      <el-form
        ref="carouselRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item
          label="轮播图图片"
          prop="carouselImg"
        >
          <el-upload
            :headers="{ 'Content-Type': 'multipart/form-data' }"
            class="carouse"
            action="#"
            :show-file-list="false"
            :auto-upload="false"
            :on-change="handleImg"
          >
            <img
              class="carouse-img"
              v-if="previewCarouse"
              :src="previewCarouse"
            />
            <el-icon
              v-else
              class="carouse-plus"
              ><Plus
            /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item
          label="所在位置"
          prop="belongPage"
        >
          <el-input
            v-model="form.belongPage"
            placeholder="请输入所在位置"
          />
        </el-form-item>

        <el-form-item
          label="跳转地址"
          prop="jumpDestination"
        >
          <el-input
            v-model="form.jumpDestination"
            placeholder="请输入跳转地址"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            type="primary"
            @click="submitForm"
            >确 定</el-button
          >
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Carousel">
import {
  listCarousel,
  getCarousel,
  delCarousel,
  addCarousel,
  updateCarousel,
} from "@/api/system/carousel";
import { ref } from "vue";

const { proxy } = getCurrentInstance();
const searchtime = ref([]);

const carouselList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const previewCarouse = ref("");
const file = ref();
const files = ref(null);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    createTime: null,
  },
  rules: {},
});

const { queryParams, form, rules } = toRefs(data);

/** 查询轮播图列表 */
function getList() {
  loading.value = true;
  listCarousel(queryParams.value).then((response) => {
    console.log(response,'返回的轮播图列表')
    carouselList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  form.value = {};
  file.value = null;
  previewCarouse.value = "";
}

// 表单重置
function reset() {
  form.value = {
    carouselId: null,
    belongPage: null,
    carouselImg: null,
    jumpDestination: null,
    createTime: null,
    updateTime: null,
  };
  proxy.resetForm("carouselRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  console.log(searchtime.value,'查询参数,jjjjjjjjj')
  if(searchtime.value){
    queryParams.value.startSift = searchtime.value[0];
    queryParams.value.endSift = searchtime.value[1];
  }else{
    queryParams.value.startSift = "";
    queryParams.value.endSift = "";
  }
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.carouselId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

function handleImg(params) {
  console.log(params,'图片参数')
  const reader = new FileReader();
  reader.onload = (e) => {
    previewCarouse.value = e.target.result;
  };
  reader.readAsDataURL(params.raw);
  const lastDotIndex = params.raw.name.lastIndexOf(".");
  if (lastDotIndex > 0 && lastDotIndex < params.raw.name.length - 1) {
    const extension = params.raw.name.substring(lastDotIndex + 1);
    if (extension === "jpg" || extension === "png") {
      file.value = params.raw;
    } else {
      proxy.$message.error("文件名不合法！");
    }
  }
}

/** 新增按钮操作 */
function handleAdd() {
  form.value = {};
  open.value = true;
  title.value = "添加轮播图";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  console.log(row,'修改的行数据')
  form.value = {};
  previewCarouse.value = row.carouselImg;
  const _carouselId = row.carouselId || ids.value;
  getCarousel(_carouselId).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改轮播图";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["carouselRef"].validate((valid) => {
    if (file.value) form.value.file = file.value;
    if (valid) {
      form.value.carouselImg = previewCarouse.value;
      console.log(form.value,'提交时的数据')
      if (form.value.carouselId != null) {
        //加入的
        if(file.value){
          form.value.file = file.value;
          const id = form.value.carouselId;
          console.log(form.value,'jjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj')
            const formdata = new FormData();
            formdata.append('belongPage', form.value.belongPage);
            formdata.append('carouselId', id);
            formdata.append('createBy', form.value.createBy);
            formdata.append('createTime', form.value.createTime);
            formdata.append('endSift', form.value.endSift);
            formdata.append('jumpDestination', form.value.jumpDestination);
            formdata.append('remark', form.value.remark);
            formdata.append('startSift', form.value.startSift);
            formdata.append('updateBy', form.value.updateBy);
            formdata.append('updateTime', form.value.updateTime);
            formdata.append('file', file.value);
            // var file = formData.get('file'); // 'file' 是<input type="file">的name属性值
            console.log(formdata.get('createTime'),'formdatahhhhhhhhhhhhhhhhhhhhhhhhhh')
             // 打印所有值
             for (var value of formdata.values()) {
                console.log("Value: " + value);
            }

            updateCarousel(formdata).then((response) => {
              proxy.$modal.msgSuccess("修改成功");
              open.value = false;
              getList();
            });
        }else{
            updateCarousel(form.value).then((response) => {
              proxy.$modal.msgSuccess("修改成功");
              open.value = false;
              getList();
            });
        }
      } else {
        console.log(form.value,'核对提交新增参数的的图片路径')
        addCarousel(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
    file.value = null;
    previewCarouse.value = "";
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _carouselIds = row.carouselId || ids.value;
  proxy.$modal
    .confirm('是否确认删除轮播图编号为"' + _carouselIds + '"的数据项？')
    .then(function () {
      return delCarousel(_carouselIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "system/carousel/export",
    {
      ...queryParams.value,
    },
    `carousel_${new Date().getTime()}.xlsx`
  );
}

getList();
</script>

<style>
.carouse {
  border: 1px dashed #8c939d;
  border-radius: 6px;
  width: 170px;
  height: 170px;
  .carouse-plus {
    font-size: 28px;
    color: #8c939d;
    width: 170px;
    height: 170px;
    text-align: center;
  }
  .carouse-img {
    width: 170px;
    height: 170px;
    object-fit: contain;
  }
}

.carouse:hover {
  border: 1px dashed cornflowerblue;
  .carouse-plus {
    color: cornflowerblue;
  }
}
</style>
